package cn.iocoder.yudao.module.cmt.service.content;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.content.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.content.ContentPostDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.content.ContentPostMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class ContentPostServiceImpl implements ContentPostService {

    @Resource
    private ContentPostMapper contentPostMapper;

    @Override
    public Long createPost(ContentPostSaveReqVO createReqVO) {
        ContentPostDO post = BeanUtils.toBean(createReqVO, ContentPostDO.class);
        contentPostMapper.insert(post);
        return post.getId();
    }

    @Override
    public void updatePost(ContentPostSaveReqVO updateReqVO) {
        validatePostExists(updateReqVO.getId());
        ContentPostDO updateObj = BeanUtils.toBean(updateReqVO, ContentPostDO.class);
        contentPostMapper.updateById(updateObj);
    }

    @Override
    public void deletePost(Long id) {
        validatePostExists(id);
        contentPostMapper.deleteById(id);
    }

    private void validatePostExists(Long id) {
        if (contentPostMapper.selectById(id) == null) {
            throw exception(POST_NOT_EXISTS);
        }
    }

    @Override
    public ContentPostDO getPost(Long id) {
        return contentPostMapper.selectById(id);
    }

    @Override
    public PageResult<ContentPostDO> getPostPage(ContentPostPageReqVO pageReqVO) {
        return contentPostMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePostListByIds(List<Long> ids) {
        ids.forEach(this::validatePostExists);
        contentPostMapper.deleteBatchIds(ids);
    }

}
